<?php

namespace app\job;

use think\queue\Job;
use think\facade\Db;
use app\common\Common;
use think\facade\Cache;

// 转化回传队列
class NewTransferBack
{
    public function fire(Job $job, $info)
    // public function fire($info)
    {
        // 获取该链接的回传相关设置
        $linkData = Db::name('link')->where(['id' => $info['link_id']])->field('is_open, media_id, echo_rate, echo_rule_config_id, official_account_id, is_open_low_recharge_not_echo, not_echo_recharge_price, edit_echo_rate_time, token, is_capitalization')->find();

        if ($linkData['is_open'] != 1) {
            // 该链接未开启回传
            $job->delete();
            return;
        }

        // 如果开启了低充值不回传并且充值低于设置的最低回传充值将不回传
        if ($linkData['is_open_low_recharge_not_echo'] == 1 && round($info['total_fee'], 2) < round($linkData['not_echo_recharge_price'], 2)) {
            $job->delete();
            return;
        }

        // 如果用户在该链接充值第一笔未回传 则不回传
        $payData = Db::name('pay_record')->where(['uid' => $info['uid'], 'status' => 1, 'link_id' => $info['link_id']])->field('id')->select();
        $transferBackRecordData = Db::name('transfer_back_record')->where(['uid' => $info['uid'], 'status' => 1, 'link_id' => $info['link_id']])->field('id')->find();

        if (count($payData) > 1 && empty($transferBackRecordData)) {
            $job->delete();
            return;
        }

        // 获取该用户在该链接的回传数据
        if (!empty($transferBackRecordData) && time() < strtotime($info['activation_time']) + 7 * 86400) {
            // 如果该用户再该链接回传过并且当前时间小于激活时间加7天的时间的话直接回传
            $boolId = $this->backPlatform($linkData, $info, 0);
            $job->delete();
            return;
        }

        // 如果当前时间大于激活时间当天23点59分59秒不回传
        $activationTime = date('Y-m-d').' 00:00:00';

        if (strtotime($info['activation_time']) < strtotime($activationTime)) {
            $job->delete();
            return;
        }

        // 获取redis对象
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $type = 0;

        $startTime = strtotime(date('Y-m-d'.' 00:00:00'));
        $endTime = strtotime(date('Y-m-d'.' 23:59:59'));
        if ($startTime < $linkData['edit_echo_rate_time'] && $endTime > $linkData['edit_echo_rate_time']) { // 当天有修改回传率
            // 按该链接修改回传率的时间之后的支付数和回传数开始计算比例
            $thisLinkOrderNum = $redis->get('update-time-pay-success-order-num-'.$info['advertiser_id'].'-'.$linkData['edit_echo_rate_time']); // 该投放计划的订单数
            $backSuccessNum  = $redis->get('update-time-echo-success-order-num-'.$info['advertiser_id'].'-'.$linkData['edit_echo_rate_time']); // 该投放计划的回传数

            if (empty($thisLinkOrderNum) || empty($backSuccessNum)) {
                $where = [
                    ['advertiser_id', '=', $info['advertiser_id']],
                    ['status', '=', 1],
                    ['pay_time', '>', $linkData['edit_echo_rate_time']],
                    ['link_id', '=', $info['link_id']]
                ];
                // 这个链接修改回传率的时间之后的支付订单数（每个用户仅统计一次）
                $thisLinkOrderNum = Db::name('pay_record')->where($where)->group('uid')->count();
                // 这个链接修改回传率的时间之后的回传成功数（每个用户仅统计一次）
                $where = [
                    ['advertiser_id', '=', $info['advertiser_id']],
                    ['status', '=', 1],
                    ['created_at', '>', $linkData['edit_echo_rate_time']],
                    ['link_id', '=', $info['link_id']],
                    ['echo_rule_config_id', '<>', '-1']
                ];
                $backSuccessNum = Db::name('transfer_back_record')->where($where)->group('uid')->count();

                $redis->set('update-time-pay-success-order-num-'.$info['advertiser_id'].'-'.$linkData['edit_echo_rate_time'], $thisLinkOrderNum, 21600); // redis存12小时
                $redis->set('update-time-echo-success-order-num-'.$info['advertiser_id'].'-'.$linkData['edit_echo_rate_time'], $backSuccessNum, 21600);
            } else {
                // 用户第一次回传
                $redis->incr('update-time-pay-success-order-num-'.$info['advertiser_id'].'-'.$linkData['edit_echo_rate_time']); // redis自增1
                $thisLinkOrderNum = $thisLinkOrderNum + 1;
            }
            $type = 1;
        } else {
            // 没有修改回传率时间则表示未修改过回传率
            $thisLinkOrderNum = $redis->get('pay-success-order-num-'.date('Ymd').'-'.$info['advertiser_id']); // 该投放计划的订单数
            $backSuccessNum = $redis->get('echo-success-order-num-'.date('Ymd').'-'.$info['advertiser_id']); // 该投放计划的回传数

            if (empty($thisLinkOrderNum) || empty($backSuccessNum)) {
                // 这个链接所有支付成功的订单数（每个用户仅统计一次）
                if (!empty($linkData['echo_rule_config_id'])) {
                    $thisLinkOrderNum = Db::name('pay_record')->where(['advertiser_id' => $info['advertiser_id'], 'status' => 1, 'activation_date' => date('Ymd'), 'link_id' => $info['link_id']])->group('uid')->count();
                } else {
                    $thisLinkOrderNum = Db::name('pay_record')->where(['advertiser_id' => $info['advertiser_id'], 'status' => 1, 'consume_date' => date('Ymd'), 'link_id' => $info['link_id']])->group('uid')->count();
                }
                // 这个链接回传成功的数量（每个用户仅统计一次）
                $where = [
                    ['link_id', '=', $info['link_id']],
                    ['advertiser_id', '=', $info['advertiser_id']],
                    ['status', '=', 1],
                    ['echo_rule_config_id', '<>', '-1'],
                    ['created_at', 'between', [$startTime, $endTime]]
                ];
                $backSuccessNum = Db::name('transfer_back_record')->where($where)->group('uid')->count();

                $redis->set('pay-success-order-num-'.date('Ymd').'-'.$info['advertiser_id'], $thisLinkOrderNum, 21600);
                $redis->set('echo-success-order-num-'.date('Ymd').'-'.$info['advertiser_id'], $backSuccessNum, 21600);
            } else {
                // 用户第一次回传
                $redis->incr('pay-success-order-num-'.date('Ymd').'-'.$info['advertiser_id']);
                $thisLinkOrderNum = $thisLinkOrderNum + 1;
            }
            $type = 2;
        }

        if (empty($thisLinkOrderNum)) {
            $thisLinkOrderNum = 1;
        }

        // 按比例回传
        if ($backSuccessNum / $thisLinkOrderNum < $linkData['echo_rate'] / 100) {
            // 小于回传比例
            $boolId = $this->backPlatform($linkData, $info, 1);
            if ($type == 1) {
                $redis->incr('update-time-echo-success-order-num-'.$info['advertiser_id'].'-'.$linkData['edit_echo_rate_time']); // redis成功回传数自增1
            } else if ($type == 2) {
                $redis->incr('echo-success-order-num-'.date('Ymd').'-'.$info['advertiser_id']);
            }
        }

        // 如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
        $job->delete();
        // 也可以重新发布这个任务
        // $job->release($delay); //$delay为延迟时间
    }

    // 付费按比例回传
    public function backPlatform($linkData, $info, $isFirst = 0)
    {
        $mediaId = $linkData['media_id'];
        $echoRuleId = $linkData['echo_rule_config_id'];

        if ($mediaId == 1) {
            // 抖音
            if (!empty($linkData['is_capitalization'])) {
                $token = config('tiktok.capitalization.token');
                $url = config('tiktok.capitalization.url');
                $timestamp = time();
                $rand = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
                shuffle($rand);

                $nonceArray = array_slice($rand, 0, 4);
                $nonce = implode('', $nonceArray);

                $collect = [(string)$token, (string)$nonce, (string)$timestamp];
                usort($collect, 'strcmp');
                $signature = sha1(implode('', $collect));

                $body = [
                    'clue_token' => $info['clickid'],
                    'open_id' => $info['open_id'],
                    'event_type' => '2',
                    'props' => [
                        'pay_amount' => intval($info['total_fee']*100)
                    ]
                ];

                $requestData = json_encode($body);
                $url = $url . '?timestamp=' . $timestamp . '&nonce=' . $nonce . '&signature=' . $signature;
                $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
                $data = json_decode($result, true);
                $status = isset($data['status']) && $data['status'] == 200 ? 1 : 2; // 1成功 2失败
                $message = !empty($data['message']) ? $data['message'] : '成功'; // 回传巨量的响应提示

            } else {
                $url = 'https://analytics.oceanengine.com/api/v2/conversion';

                $requestData = [
                    'event_type' => 'active_pay',
                    'event_weight' => floatval($info['total_fee']*100),
                    'context' => [
                        'ad' => [
                            'callback' => $info['clickid']
                        ]
                    ],
                    'properties' => [
                        'pay_amount' => floatval($info['total_fee']*100),
                        'bill_track_type' => '1'
                    ],
                    'timestamp' => Common::msectime()
                ];

                $requestData = json_encode($requestData);
                $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
                $data = json_decode($result, true);
                $status = isset($data['code']) && $data['code'] == 0 ? 1 : 2; // 1成功 2失败
                $message = !empty($data['message']) ? $data['message'] : ''; // 回传巨量的响应提示
            }

        } else if ($mediaId == 2) {
            // 快手 https://yiqixie.qingque.cn/d/home/fcACjQFu3lSI1QT7ktc7TCH9e#
            $url = 'http://ad.partner.gifshow.com/track/activate';
            $requestData = [
                'callback' => $info['clickid'],
                'event_type' => 3,
                'event_time' => Common::msectime(),
                'purchase_amount' => $info['total_fee']
            ];

            $result = Common::_curl($url, $requestData, 'GET');
            $data = json_decode($result, true);
            $status = isset($data['result']) && $data['result'] == 1 ? 1 : 2;
            $message = !empty($data['error_msg']) ? '失败' : '成功';

        } else if ($mediaId == 3) {
            // 百度
            $url = 'https://ocpc.baidu.com/ocpcapi/api/uploadConvertData';
            $conversionTypes = [
                'logidUrl' => 'https://'.config('app.app_host').'?bd_vid='.$info['clickid'],
                'newType' => 118,
                'convertValue' => intval($info['total_fee']*100)
            ];

            $token = $linkData['token'];
            $datas = ['token' => $token, 'conversionTypes' => $conversionTypes];
            $requestData = json_encode($datas);
            $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
            $data = json_decode($result, true);
            $status = $data['header']['status'] == 0 ? 1 : 2;
            $message = !empty($data['header']['errors']) ? $data['header']['errors']['message'] : '成功';
        }

        // 组装回传记录数据
        $saveData = [
            'uid' => $info['uid'],
            'pay_id' => $info['id'],
            'media_id' => $mediaId,
            'link_id' => $info['link_id'],
            'created_at' => time(),
            'status' => $status,
            'message' => $message,
            'echo_rule_config_id' => $linkData['echo_rule_config_id'],
            'official_account_id' => $linkData['official_account_id'],
            'is_first_recharge' => $isFirst,
            'version' => 2,
            'advertiser_id' => $info['advertiser_id'],
        ];

        // 添加回传记录
        Db::name('transfer_back_record')->insert($saveData);
        // 修改订单表数据是否回传 等于0表示成功
        if ($status == 1) {
            Db::name('pay_record')->where(['id' => $info['id']])->update(['is_echo' => 1]);
        }
        return true;
    }

    public function failed($data)
    {
        // ...任务达到最大重试次数后，失败了
    }
}